﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Trirand.Web.Mvc;

namespace Catalyst.Mvc
{
	public partial class LiteGrid<TGrid>
	{
		private string m_ClientSideOnDocumentReady = "";
		internal string ClientSideOnDocumentReady { get { return m_ClientSideOnDocumentReady; } private set { m_ClientSideOnDocumentReady = value; } }

		public void AddColumnDependency(ColumnDependency columnDependency)
		{
			ColumnDependencies.Add(columnDependency);

			ClientSideEvents.AfterEditDialogShown = "populateDependentColumnsDialogue";
			ClientSideEvents.AfterAddDialogShown = "populateDependentColumnsDialogue";
		}

		public void AppendToGridInitializedScripts(string script)
		{
			ClientSideEvents.GridInitialized += script + "\r\n";
		}

		public void AppendToOnDocumentReadyScripts(string script)
		{
			ClientSideOnDocumentReady += script + "\r\n";
		}

		internal void CombineGridInitializedFunctions()
		{
			StringBuilder gridInitialized = new StringBuilder();
			gridInitialized.AppendLine("function() {");
			gridInitialized.Append(ClientSideEvents.GridInitialized);

			// column dependencies script
			ColumnDependency dependency = null;

			string functionName = null;
			string gridId = null;

			for (int i = 0; i < ColumnDependencies.Count; i++)
			{
				dependency = ColumnDependencies[i];

				if (HierarchySettings.HierarchyMode == HierarchyMode.Child
					|| HierarchySettings.HierarchyMode == HierarchyMode.ParentAndChild)
				{
					functionName = "addChildColumnDependencies";
					gridId = ParentGridID;
				}
				else
				{
					functionName = "addColumnDependencies";
					gridId = ID;
				}

				gridInitialized.AppendLine(String.Format("{0}('{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}'{10});",
					functionName,
					ID,
					dependency.ParentColumn,
					dependency.ChildColumn,
					String.Format("/{0}/{1}", getCurrentControllerName(), dependency.ChildAjaxDataMethod.Method.Name),
					dependency.LoadingText,
					dependency.HeadingText,
					dependency.DataTextField,
					dependency.DataValueField,
					dependency.NullParentDataValue,
					(!String.IsNullOrEmpty(dependency.OnChange) ? ", function(rowId, columnDependency) { " + dependency.OnChange + "(rowId, columnDependency); }" : "")));
			}

			gridInitialized.AppendLine("}");

			ClientSideEvents.GridInitialized = gridInitialized.ToString();
		}
	}
}
